<?php
namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Support\Facades\Storage;
use Session;
class LoginController extends Controller
{
	public function login(Request $request)
	{
		$username = $request->get('username');
		$request_code = $request->get('code');
        $session_code = $request->session()->get('milkcaptcha');
        if($request_code != $session_code){
            return response()->json(['code'=>0,'info'=>'验证码错误']);
            exit;
        }
		//pan duan username shi fou cun zai
		$isusername = DB::table('user')->where('username',$username)->first();
		if(!$isusername){
			return response()->json(['code'=>0,'info'=>'查不到此账户']);
			exit;
		}
		//pan duan password
		if(md5($request->get('password')) != $isusername->password){
			return response()->json(['code'=>0,'info'=>'密码错误']);
		}else{
			// take the user's messgae into session
			$request->session()->put(['id'=>$isusername->id,'username'=>$isusername->username]);
			return response()->json(['code'=>1]);
		}

	}

	/**
	* 验证码
	*/
	public function text($tmp){
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40);
        //获取验证码的内容
        $phrase = $builder->getPhrase();
        // var_dump($phrase);
        //把内容存入session
        Session::flash('milkcaptcha', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        return response($builder->output())->header('Content-type','image/jpeg');
	}

	/**
     * 测试
	*/
	public function my()
    {
        $name = ['张三','里斯','王二','麻子','素素','gugu'];
        return view('Home/login/justtext')->with(['name'=>$name]);
    }
    public function name()
    {
        $name = ['张三','里斯','王二','牛牛','素素','gugu','养成','顾景','小三','张吃'];
        return response()->json(['name'=>$name]);
    }
    public function upload(Request $request)
    {
        if($request->isMethod('post')){
            $file = $request->file('img');
            if($file->isValid()){
                $originName = $file->getClientOriginalName();
                $etc = $file->getClientOriginalExtension();
                $realpath = $file->getRealPath();
                $filename = date('YmdHis',time()).'-'.uniqid().'.'.$etc;
                $bool = Storage::disk('upload')->put($filename,file_get_contents($realpath));
                if(!$bool){
                    return response()->json(['code'=>0,'info'=>'系统繁忙，请重试']);
                }else{
                    return response()->json(['code'=>1,'filename'=>$filename]);
                }
            }
        }
    }

    /*
     *退出登陆
     */
    public function logout(Request $request)
    {
        $res = $request->session()->forget(['id','username']);
        return redirect('home/login');
    }
}